package org.exez.modules.visitor.api;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.exez.common.api.vo.Result;
import org.exez.common.aspect.annotation.AutoLog;
import org.exez.common.constant.CommonConstant;
import org.exez.common.exception.JeecgBootException;
import org.exez.common.system.base.controller.JeecgController;
import org.exez.common.system.util.JwtUtil;
import org.exez.common.system.vo.LoginUser;
import org.exez.common.util.PasswordUtil;
import org.exez.common.util.RedisUtil;
import org.exez.modules.system.entity.SysUser;
import org.exez.modules.system.service.ISysUserService;
import org.exez.modules.visitor.api.vo.WhiteListDeletedByApiVO;
import org.exez.modules.visitor.api.vo.WhiteListUpdateByApiVO;
import org.exez.modules.visitor.dto.terminal.DeviceTerminalDTO;
import org.exez.modules.visitor.dto.terminal.SysLoginDTO;
import org.exez.modules.visitor.dto.terminal.VisitorReservationDTO;
import org.exez.modules.visitor.entity.Institution;
import org.exez.modules.visitor.entity.ReservationApplication;
import org.exez.modules.visitor.entity.WhiteList;
import org.exez.modules.visitor.service.*;
import org.exez.modules.visitor.util.AESSJY;
import org.exez.modules.visitor.util.UploadUtil;
import org.exez.modules.visitor.vo.AccessRecordVo;
import org.exez.modules.visitor.api.vo.WhiteListSaveByApiVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @Description: 外部接口接受数据
 * @Author: exez-boot
 * @Date: 2020-06-04
 * @Version: V1.0
 */
@Slf4j
@Api(tags = "外部接口接受数据")
@RestController
@RequestMapping("/exez")
public class ExezController extends JeecgController<ReservationApplication, IReservationApplicationService> {

    @Value("${url.mogo-upload}")
    private String uploadUrl;


    @Value("${url.mogo-view}")
    private String fileView;


    @Autowired
    private SjyService sjyService;

    @Autowired
    private IReservationApplicationService reservationApplicationService;

    @Autowired
    private IDeviceService deviceService;


    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private IVisitorAccessreService visitorAccessreService;

    @Autowired
    private IWhiteListService whiteListService;

    @Autowired
    private IInstitutionService institutionService;

    @ApiOperation("登录接口")
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public Result<String> login(@Validated @RequestBody SysLoginDTO sysLoginModel) {
        Result<String> result = new Result<>();
        String username = sysLoginModel.getClientId();
        String password = sysLoginModel.getSecret();

        //1. 校验用户是否有效
        SysUser sysUser = sysUserService.getUserByName(username);

        if (null == sysUser){
            result.error500("用户不存在");
            return result;
        }
        //2. 校验用户名或密码是否正确
        String userpassword = PasswordUtil.encrypt(username, password, sysUser.getSalt());
        String syspassword = sysUser.getPassword();
        if (!syspassword.equals(userpassword)) {
            result.error500("用户名或密码错误");
            return result;
        }

        //用户登录信息
        String token = userInfo(sysUser);
        result.successSetDate(token);

        return result;
    }


    @ApiOperation("applicationDataDistribution")
    @RequestMapping(value = "/applicationDataDistribution", method = RequestMethod.POST)
    public Result<Integer> applicationDataDistribution() {
        Result<Integer> result = new Result<>();

        Boolean aBoolean = sjyService.applicationDataDistribution();
        result.successSetDate(0);
        return result;
    }

    @ApiOperation("whiteListDataDistribution")
    @RequestMapping(value = "/whiteListDataDistribution", method = RequestMethod.POST)
    public Result<Integer> whiteListDataDistribution() {
        Result<Integer> result = new Result<>();

        Boolean aBoolean = sjyService.whiteListDataDistribution();
        result.successSetDate(0);
        return result;
    }



    @ApiOperation("设备注册接口")
    @RequestMapping(value = "/deviceRegistration", method = RequestMethod.POST)
    public Result<String> deviceRegistration(@Validated @RequestBody DeviceTerminalDTO deviceTerminalDTO) {

        log.info("[{}]deviceTerminalDTO++", JSON.toJSONString(deviceTerminalDTO));
        Result<String> result = new Result<>();

        deviceService.saveDevice(deviceTerminalDTO);
        return result;
    }



    @ApiOperation("访客登记接口")
    @RequestMapping(value = "/visitorRegistration", method = RequestMethod.POST)
    public Result<Integer> deviceRegistration(@Validated @RequestBody VisitorReservationDTO visitorReservationDTO) {
        Result<Integer> result = new Result<>();
        reservationApplicationService.saveReservationByDevice(visitorReservationDTO);
        result.successSetDate(0);
        return result;
    }



    /**
     * 出入记录---对外接口
     *
     * @return
     */
    @ApiOperation(value = "出入记录---对外接口", notes = "出入记录---对外接口")
    @PostMapping(value = "/accessRecord")
    public Result<String> accessRecord(
            @RequestBody @Validated AccessRecordVo accessRecordVo){
        System.out.println("推送出入记录进来了。。。。。。");
        String photo = visitorAccessreService.insertVisitorAccess(accessRecordVo);
        Result<String> objectResult = new Result<>();
        objectResult.successSetDate(fileView + photo);
        return objectResult;
    }





    /**
     * 添加
     *
     * @param whiteListSaveVO
     * @return
     */
    @AutoLog(value = "白名单-添加", logType = 3, operateType = 2)
    @ApiOperation(value = "白名单-添加", notes = "白名单-添加")
    @PostMapping(value = "/whiteList/add")
    public Result<String> add(@Validated @RequestBody WhiteListSaveByApiVO whiteListSaveVO) {
        Result<String> result = new Result<>();

        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        WhiteList whiteList = new WhiteList();
        BeanUtils.copyProperties(whiteListSaveVO,whiteList);

        Institution institutionByCode = institutionService.getInstitutionByCode(whiteListSaveVO.getInstitutionCode());

        whiteList.setInstitutionId(institutionByCode.getId());
        whiteList.setCreateBy(sysUser.getId());
        whiteList.setUpdateBy(sysUser.getId());

        String facePhoto = UploadUtil.upload(uploadUrl, whiteListSaveVO.getFacePhoto());
        whiteList.setFacePhoto(fileView + facePhoto);

        String s = whiteListService.saveWhiteList(whiteList);
        result.successSetDate(s);
        return result;
    }

    /**
     * 编辑
     *
     * @param whiteListUpdateVO
     * @return
     */
    @AutoLog(value = "白名单-编辑", logType = 3, operateType = 3)
    @ApiOperation(value = "白名单-编辑", notes = "白名单-编辑")
    @PostMapping(value = "/whiteList/edit")
    public Result<String> edit(@RequestBody WhiteListUpdateByApiVO whiteListUpdateVO) {
        whiteListService.updateWhiteListByIdentityValue(whiteListUpdateVO);
        return Result.ok("编辑成功!");
    }


    /**
     * 通过id删除
     *
     * @param whiteListDeletedByApiVO
     * @return
     */
    @AutoLog(value = "通过身份证删除白名单", logType = 3, operateType = 4)
    @ApiOperation(value = "通过身份证删除白名单", notes = "通过身份证删除白名单")
    @GetMapping(value = "/whiteList/delete")
    public Result<String> delete(@RequestBody WhiteListDeletedByApiVO whiteListDeletedByApiVO) {
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();

        String s = AESSJY.AESjiemi(whiteListDeletedByApiVO.getIdentityValue());

        Institution institutionByCode = institutionService.getInstitutionByCode(whiteListDeletedByApiVO.getInstitutionCode());

        LambdaQueryWrapper<WhiteList> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(WhiteList :: getIdentityValue,s);
        queryWrapper.eq(WhiteList :: getInstitutionId,institutionByCode.getId());
        queryWrapper.eq(WhiteList :: getDeleted,1);

        WhiteList one = whiteListService.getOne(queryWrapper);
        if (null == one){
            throw new JeecgBootException("不存在该用户");
        }

        WhiteList whiteList = new WhiteList();
        whiteList.setId(one.getId());
        whiteList.setUpdateBy(sysUser.getId());
        whiteList.setDeleted(0);
        whiteList.setUpdateTime(new Date());

        List<WhiteList> whiteLists = new ArrayList();
        whiteLists.add(whiteList);
        whiteListService.deletedWhiteList(whiteLists);
        return Result.ok("删除成功!");
    }




    /**
     * 用户信息
     *
     * @param sysUser
     * @return
     */
    private String userInfo(SysUser sysUser) {
        String syspassword = sysUser.getPassword();
        String username = sysUser.getUsername();
        // 生成token
        String token = JwtUtil.sign(username, syspassword);
        // 设置token缓存有效时间
        redisUtil.set(CommonConstant.PREFIX_USER_TOKEN + token, token);
        redisUtil.expire(CommonConstant.PREFIX_USER_TOKEN + token, JwtUtil.EXPIRE_TIME * 2 / 1000);

        return token;
    }


}
